<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class MY_Controller extends CI_Controller {

    public $userinfo='';
    public $user_id="";
    public $username="";
    public $status="";
    public $address='';//页面位置
    public $group=0; //用户组
    public $project=0;  //所属项目  1京东  2拼多多


    public function __construct() {
        parent::__construct();
        $class= $this->checklogin();
        if ($class != 'welcome') {
            $this->initialinfo();
        }
    }


    public function initialinfo(){
        $userinfo= $this->session->userinfo;
        if(!isset($userinfo['group'])){
            $this->userinfo=$this->getcuserinfo(1);
            $this->setuserinfo( $this->userinfo);
        }else{
            $this->userinfo=$userinfo;
        }
        $this->group=$userinfo['group'];
        $this->user_id=$this->session->user_id;

    }


    public function checklogin(){
        $this->load->helper('url');
        $this->load->library('session');
        if (!$this->session->islogin) {
            $class=$this->router->class;
            if(strtolower($class)=='welcome'){
                return  strtolower($class);
            } else {
                $arr =array();
                $arr['status'] = -1;
                $arr['message'] = '未登录';
                redirect(base_url() . '/Welcome/register');
            }
        }
    }


    /**
     * 根据不同身份进行跳转
     * @param $group
     */
    public function groupjunp($group){
        if($group==1 ||$group==4||$group==5||$group==6){
            redirect(base_url() . '/Customer/index');
        }
        if($group==2){
            redirect(base_url() . '/business/index');
        }
        if($group==3){
            redirect(base_url() . '/hunter/index');
        }
    }





    public function sendjsonmsg($row=array()){
        if(empty($row['code'])){
            $row['code']=0;
        }
        if(empty($row['msg'])){
            $row['msg']="无消息";
        }
        echo json_encode($row);   exit;
    }


    /**
     * 获取用户信息
     */
    public function getcuserinfo($getall=0,$user_id=0){
        $userinfo=  $this->userinfo= $this->session->userinfo;
        if($getall==1 || empty($userinfo)){
            if(empty($user_id)){
                $user_id= $this->session->user_id;
            }
            $this->load->model('Jd_users_model');
            $userinfo=$this->Jd_users_model->GetUserById($user_id );
            $userinfo=$userinfo;
        }
        return $userinfo;
    }




   public function  ResetUserinfo(){
        $userinfo=$this->getcuserinfo(1);
        $this->setuserinfo($userinfo);
   }

    /**
     * 设置用户信息
     */
    public function setuserinfo($userinfo){
        $this->user_id=$userinfo['id'];
        $this->username=$userinfo['username'];

        if(empty($userinfo['team'])){
            $userinfo['team']="";
        }else{
            $this->load->model('Jd_group_model');
            $userinfo['team']=$this->Jd_group_model->getteambyuserid( $userinfo['team']);
        }
        $this->session->userinfo = $userinfo;
        $this->session->username = $userinfo['username'];

    }


    /**
     * 设置推广链接
     * @param $user_id
     */
    public function SetExtensionLink($user_id,$type='reg_invite'){
             $link= base_url()."welcome/sign/";
             $key=$type.$user_id;
             $key =base64_encode($key);
             $key=urlencode($key);
             $link=$link.$key;
             return $link;
    }

    /**
     * 将URL格式的字符串转化为ID
     *
     * @param String $str
     * @return Array(goods_type, goods_id)
     */
   public function Url2Key($key,$type='reg_invite') {
        $key = base64_decode ( urldecode ( $key ) );
        return explode ($type, $key );
    }




    public function getgrouplist($type=0){
        $this->load->model('Jd_group_model');
        $r=  $this->Jd_group_model->getgrouplist();
        if($type){
            $lsit=array();
            foreach ($r as $id=>$v){
                $lsit[$v['id']]=$v['name'];
            }
            return $lsit;
        }
        return $r;
    }
    public function getteamlist($type=0){
        $this->load->model('Jd_group_model');
        $r=  $this->Jd_group_model->getteamlist();

        if($type){
            $lsit=array();
            foreach ($r as $id=>$v){
                $lsit[$v['id']]=$v['name'];
            }
            return $lsit;
        }
        return $r;
    }
    public function getchannellist($type=0){
        $this->load->model('Jd_group_model');
       $r=  $this->Jd_group_model->getchannellist();
       if($type){
           $lsit=array();
           foreach ($r as $id=>$v){
               $lsit[$v['id']]=$v['name'];
           }
           return $lsit;
       }
       return $r;
    }





    /**
     * 增量更新用户信息
     */
    public  function UpdataUserinfo($row,$user_id){
        $this->load->model('jd_user_total_model');
        $sql='update jd_user_total set ';
        $array=array();
        $array[]='task_nub';
        $array[]='task_nub_finnish';
        $array[]='extension';
        $array[]='extension_nub';

        if(isset($row['update'])){//如果有更新日期则为 邀请统计
            $update=$this->jd_user_total_model->getonebyuserid($user_id,'update');
            $date=$row['update'];
            $sql="update jd_user_total set   `update`='$date',  extension_nub_day=1, ";
            if(isset($update[0]['update']) &&!empty( $update[0]['update'])){
                   if($update[0]['update']==$row['update']){
                       $sql="update jd_user_total set   `update`='$date',";
                       $array[]='extension_nub_day';
                   }
            }
        }
        $newrow=array();
        if(!empty($row)){
            foreach ($row as $id=>$v){
                if(in_array($id,$array)){
                    $newrow[]="$id=$id+$v";
                }
            }
        }
        $newrow=implode(",",$newrow);
        $sql=$sql.' '.$newrow ;
        $sql.=" where user_id=".$user_id;
        return  $result=  $this->jd_user_total_model->updata_user_total($sql,$user_id);
    }


    /**
     * 商户资金检测
     */
    public function checkmoney($allmoney,$allgold){
        $this->userinfo= $this->getcuserinfo(1,$this->user_id);
        $money=$this->userinfo['money'];
        $gold=$this->userinfo['gold'];
        if($allmoney>$money){
            return false;
        }
        if($allgold>$gold){
            return false;
        }
        return  true;
    }

    /**
     * 用户资金变动
     * @param $row 变动的资金参数
     * @param string $type  资金变动类型 主要用于log记录 1 :充值 2发布任务 3 推荐奖励 4刷单,5兑换金币,6后台调整
     */
    public function moneyupdate($row,$type="",$log_id=""){
        if(empty($row['user_id'])){
            $msg['code']=2;
            $msg['msg']="资金变动缺少用户ID";
            $this->sendjsonmsg($msg);
        }
        $user_id=$row['user_id'];
        $row= $this->chekemoneytype($row,$type);
        $this->load->model('Jd_users_model');
        $sql='update jd_users set ';
        $newrow=array();
        if(!empty($row)){
            foreach ($row as $id=>$v){
                if($id!="money" && $id!="gold"){
                 continue;
                }
                if($v<0){
                    $v=-$v;
                    $newrow[]="$id=$id-$v";
                }else{
                    $newrow[]="$id=$id+$v";
                }

            }
        }
        $newrow=implode(",",$newrow);
        $sql=$sql.' '.$newrow  ;
        $result=  $this->Jd_users_model->updata_user_money($sql,$user_id);
        if($result){
            $row['log_id']=$log_id;
            $row['user_id']=$user_id;
            $resl= $this->addpaylog($row,$type);
            return $resl;
        }else{
            return false;
        }
    }


    /**
     * 用EXCEL导出内容
     * @param $str
     * @param $list
     * @param $filename
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Writer_Exception
     */
    public function excel_out($str,$list,$filename){
        $this->load->library('PHPExcel');
        $objPHPExcel = new PHPExcel();
        $filename =$filename.date('Y-m-d H:i:s').'.xls';
        $i = 1;

        $row=array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
        foreach ($str as $id=>$v){
            $objPHPExcel->getActiveSheet()->setCellValue($row[$id].$i , $v);
        }
        foreach($list as $val) {
            $i++;
            $x=0;
            foreach ($val as $id=>$v){
                $objPHPExcel->getActiveSheet()->setCellValue($row[$x].$i , $v);
                $x++;
            }
        }
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="'.$filename.'"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }


    /*
     * 检测资本变动类型
     */
    public  function  chekemoneytype($row,$type){

        if(in_array($type,array(2,4,5))) {//如果是刷单  发布任务和 兑换金币 则钱减少
            $row['money']= -abs($row['money']);
        }
        if(isset( $row['gold'])){
           if($type==2){
               $row['gold']= -abs($row['gold']);
           }
        }
        return $row;
    }



    /**
     * type 1 :充值 2发布任务 3 推荐奖励 4刷单,5兑换金币,6后台调整
     * 用户资金记录添加
     */
    public function  addpaylog($row,$type){
        if(empty($row['gold'])){
            $row['gold']=0;
        }
        if(empty($row['money'])){
            $row['money']=0;
        }
        if(empty($row['user_id'])){
            return false;
        }
        $this->load->model('Jd_pay_log_model');
        $userinf=$this->getcuserinfo(1,$row['user_id']);


        $row['capital']=$userinf['money']-$row['money'];
        $row['capital_gold']=$userinf['gold']-$row['gold'];
        $row['balance']=$userinf['money'];
        $row['balance_gold']=$userinf['gold'];
        $row['user_type']=$userinf['group'];
        $row['type']=$type;
        $remarks='';
        switch ($type){
            case 1 :$remarks='充值';break;
            case 2 :$remarks='任务发布';break;
            case 3 :$remarks='推荐奖励';break;
            case 4 :$remarks='刷手刷单';break;
            case 5 :$remarks='兑换金币';break;
            case 6 :$remarks='后台调整';break;
        }
        if(empty( $row['remarks'])){
            $row['remarks']=$remarks;
        }
        $row['log_type']=$this->project;



         return  $this->Jd_pay_log_model->addpaylog($row);
    }


    /**
     * 获取佣金
     */
    public function getcommission($money,$user_id=0,$project=1){
        $this->load->model('Jd_users_model');
        $this->project=$project;
        $userinf=$this->session->userinfo;
        if(empty($userinf['commission'])){
            $userinf=$this->Jd_users_model->GetUserById($user_id,"commission,commission2");
        }
        if($this->project==1){
            $commission=$userinf['commission'];
        }else{
            $commission=$userinf['commission2'];
        }
        if(!empty($commission)){
            $commission=unserialize($commission);
        }else{
            if($this->project==1){
                $commission=array(200,100,100,10);
            }else{
                $commission=array(200,100,100,10);
            }
        }
        $gold=0;
        if($money<$commission[0]){
            $gold=$commission[1];
        }else{
           $nub=  ceil(($money-$commission[0])/$commission[2]);
           $gold=$commission[1]+$nub*$commission[3];
        }
        return  $gold;
    }


    /**
     * 上传图片
     */
    public function  uppic(){
        $file = $_FILES['uploadFile'];//得到传输的数据
        $msg['code']=1;

        if($file['error']>0){
            $msg['msg']="错误类型".$file['error'];
            $this->sendjsonmsg($msg);
        }

        $name = $file['name'];
        $type = strtolower(substr($name,strrpos($name,'.')+1)); //得到文件类型，并且都转化成小写
        $allow_type = array('jpg','jpeg','gif','png'); //定义允许上传的类型

        if(!in_array($type, $allow_type)){
            $msg['msg']="不允许上传".$type."型的文件";
            $this->sendjsonmsg($msg);
        }
        if(!is_uploaded_file($file['tmp_name'])){
            return ;
        }
        $upload_path =UPLOADS."/temporary/"; //上传文件的存放路径
        $r= move_uploaded_file($file['tmp_name'],$upload_path.$file['name']);
        if($r){
            $msg['code']=0;
            $msg['msg']="上传成功";
            $msg['url']=base_url()."public/uploads/temporary/".$file['name'];
            $msg['path']=$upload_path.$file['name'];
            $this->sendjsonmsg($msg);
        }
        $msg['msg']="上传失败";
        $this->sendjsonmsg($msg);
    }


    public function movepic($file){
        $filestr=explode(".",$file);


        $count=count($filestr);
        $type=$filestr[$count-1];

        $newFile =UPLOADS."/pic/".date('Y-m-d')."/";
        if(!is_dir($newFile)){
            $res=mkdir($newFile,0777,true);
        }
        $newFile2=time().".".$type;
        $newFile=$newFile.$newFile2;
        $url="/pic/".date('Y-m-d')."/".$newFile2;
        $r=copy($file,$newFile); //拷贝到新目录
        if(!$r){
            return false;
        }
        //unlink($file); //删除旧目录下的文件
        $row['path']=$newFile;
        $row['url']=$url;
        return $row;
    }


    public function  MyRedis($type=0){
        $config= $this->config->item('redis');
        require_once(FCPATH.'application/libraries/MYredis.php');
        return MYredis::getInstance($config,$type);
    }



    public  function  Resetpoolsnumber(){
        $this->load->model('Jd_task_jd_list_pool_model');
        $result=$this->Jd_task_jd_list_pool_model->getpoolsnumber();
        $redis=$this->MyRedis();
        foreach ($result as $id=>$v){
            $redis->set('poolnub'.$v['type'],$v['num']);
        }
        echo   $redis->get('poolnub1')."__". $redis->get('poolnub2'); exit;
    }






}
